import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../common/ScreenAdaper.dart';
import '../../services/SearchServices.dart';
import 'package:dio/dio.dart';
import '../../config/Config.dart';
import '../../widget/Tool.dart';

class SearchPage extends StatefulWidget {
  final Map arguments;
  SearchPage({this.arguments});
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String _keywords = "";
  List _historyListData = [];
  List _clickHotData = [];

  // 获取历史搜索
  _getHistoryData() async {
    var _historyListData = await SearchServices.getHistoryList();
    setState(() {
      this._historyListData=_historyListData;
    });
  }
  // 获取热点小说
  _getClickHotDate() async{
    var apiUrl = "${Config.domain}api/book/hot_click?num=10";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(list['code'] == 1){
      setState(() {
        this._clickHotData = list["data"];
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getHistoryData();
    _getClickHotDate();
  }


  @override
  Widget build(BuildContext context) {
    S.init(context);
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          InkWell(
            child: Container(
              color:Colors.white,
              width: S.width(100),
              child: Row(
                children: <Widget>[
                  Text("搜索",style: TextStyle(fontSize: S.size(36))),
                ],
              ),
            ),
            onTap: (){
              SearchServices.setHistoryData(this._keywords);
              Navigator.pushNamed(context, "/list", arguments: {
                "keywords":this._keywords
              });
//              Navigator.pushReplacementNamed(context, '/list',arguments: {
//                "keywords":this._keywords
//              });
            },
          )
        ],
        title: Container(
          child: TextField(
            autofocus: true,
            decoration: InputDecoration(
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(30),
                    borderSide: BorderSide.none
                )
            ),
            onChanged: (value){
              setState(() {
                this._keywords = value;
              });
            },
          ),
          height: S.height(58),
          decoration: BoxDecoration(
              color: Color.fromRGBO(233, 233, 233, 0.8),
              borderRadius: BorderRadius.circular(30)
          ),
        ),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: ListView(
          children: <Widget>[
            _historyTitle(context),
            _historyList(),
            SizedBox(height: S.height(20)),
            Divider(height: 1, color: Colors.black38,),
            Container(
              margin: EdgeInsets.only(top: S.height(20)),
              child: Text("热门搜索", style: Theme.of(context).textTheme.title),
            ),
            _clickHotData.length > 0 ? _hotSearch() : Tool.Loading(),
          ],
        ),
      ),
    );
  }

  // 单个删除历史记录
  _showAlertDialog(keywords) async{
    var result= await showDialog(
        barrierDismissible:false,   //表示点击灰色背景的时候是否消失弹出框
        context:context,
        builder: (context){
          return AlertDialog(
            title: Text("提示信息!"),
            content:Text("您确定要删除吗?") ,
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: (){
                  print("取消");
                  Navigator.pop(context,'Cancle');
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () async{
                  //注意异步
                  await SearchServices.removeHistoryData(keywords);
                  this._getHistoryData();
                  Navigator.pop(context,"Ok");
                },
              )
            ],

          );
        }
    );
  }

  // 热门搜索
  Widget _hotSearch(){
    return Container(
      child: ListView.builder(
          itemCount: _clickHotData.length,
          shrinkWrap: true, // 解决无限高度问题
          physics: new NeverScrollableScrollPhysics(), // 禁用滑动事件
          itemBuilder: (context,index){
            return Container(
              padding: EdgeInsets.only(left: 10,top: 10,right: 10),
              child: Column(
                children: <Widget>[
                  GestureDetector(
                    child: Row(
                      children: <Widget>[
                        _sortBox(index),
                        Container(
                          margin: EdgeInsets.only(left: S.width(20)),
                          width: S.getScreenWidth() - S.width(200),
                          child: Text(
                            "${_clickHotData[index]["Name"]}",
                            overflow: TextOverflow.ellipsis,maxLines: 1,
                            style: TextStyle(fontSize: S.size(36)),
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerRight,
                          child: Icon(Icons.camera,color: Colors.red,),
                        ),

                      ],
                    ),
                    onTap: (){
                      Navigator.pushNamed(context, "/book", arguments: {
                        "bookId":_clickHotData[index]["BookId"]
                      });
                    },
                  ),
                  Container(child: Divider(height: 1,),margin: EdgeInsets.only(top:10),)
                ],
              ),
            );
          }),
    );
  }
  // 排序正方块
  Widget _sortBox(int index){
    int i = index + 1;
    switch (i) {
      case 1:
        return Container(
          alignment: Alignment.center,
          width: S.width(40),
          height: S.width(40),
          child: Text("${i}",style: TextStyle(color: Colors.white),),
          color: Colors.red,
        );
        break;
      case 2:
        return Container(
          alignment: Alignment.center,
          width: S.width(40),
          height: S.width(40),
          child: Text("${i}",style: TextStyle(color: Colors.white),),
          color: Colors.deepOrangeAccent,
        );
        break;
      case 3:
        return Container(
          alignment: Alignment.center,
          width: S.width(40),
          height: S.width(40),
          child: Text("${i}",style: TextStyle(color: Colors.white),),
          color: Colors.amberAccent,
        );
        break;
      default:
        return Container(
          alignment: Alignment.center,
          width: S.width(40),
          height: S.width(40),
          child: Text("${i}",style: TextStyle(color: Colors.white),),
          color: Colors.black12,
        );
        break;
    }
  }
  // 搜索历史
  Widget _historyTitle(context){
    return Container(
      child: Stack(
        children: <Widget>[
          Align(
            alignment: Alignment.centerLeft,
            child: Text("搜索历史", style: Theme.of(context).textTheme.title),
          ),
          Align(
            alignment: Alignment.centerRight,
            child: InkWell(
              child: Icon(Icons.delete_outline,size: S.size(50),color: Colors.black54,),
              onTap: (){
                _alertDialog("您确定要删除所有信息吗?");
              },
            ),
          ),
        ],
      ),
    );
  }
  Widget _historyList(){
    return Wrap(
      children: _historyListData.map((value){
        return Container(
          padding: EdgeInsets.all(S.width(16)),
          margin: EdgeInsets.all(S.width(16)),
          decoration: BoxDecoration(color: Color.fromRGBO(233, 233, 233, 0.9),borderRadius: BorderRadius.circular(10)),
          child: InkWell(
            child: Text("${value}"),
            onTap: (){
              Navigator.pushNamed(context, '/list',arguments: {
                "keywords":value
              });
            },
            onLongPress: (){
              this._showAlertDialog("${value}");
            },
          ),
        );
      }).toList(),
    );
  }

  // 删除弹出
  _alertDialog(title) async{
    if(title == ""){
      title = "您确定要删除吗?";
    }
    await showDialog(
        barrierDismissible:true,   //表示点击灰色背景的时候是否消失弹出框
        context:context,
        builder: (context){
          return AlertDialog(
            title: Text("提示信息!"),
            content:Text("${title}") ,
            actions: <Widget>[
              FlatButton(
                child: Text("确定"),
                onPressed: (){
                  print("确定");
                  Navigator.pop(context,"Ok");
                  SearchServices.clearHistoryList();
                  this._getHistoryData();
                },
              ),
              FlatButton(
                child: Text("取消"),
                onPressed: (){
                  print("取消");
                  Navigator.pop(context,'Cancle');
                },
              ),
            ],
          );
        }
    );
  }
}






